# function for updating data or something...

# 2015-06-30 - done
# changed Project status choices
from prd_order.models import *
Project.objects.filter(status='I').update(status='A')
Project.objects.filter(status='W').update(status='B')
Project.objects.filter(status='F').update(status='X')
Project.objects.filter(status='C').update(status='Z')


# 2015-07-01 - done
# all apps' product id add prefix: CD
from app_info.models import *
for app in App.objects.all():
    app.prd_id = 'CD%s' % app.prd_id
    app.save()


# 2015-07-02 - done
# all app version add attr: date_released
from app_info.models import *
for v in AppVersion.objects.filter(date_released=None):
    v.date_released = v.get_release_date() or None
    v.save()


# import live app database - done
import csv
from app_info.models import *
App.objects.filter(prj_code='TOBI001a').update(prj_code='TOBI001pro', old_prj_code='TOBI001a')
with open('/home/develop/Live Apps Database - Live Apps.csv') as f:
    reader = csv.DictReader(f)
    for l, r in enumerate(reader, 2):
        studio_id, studio_name = r['Publish Studio'].split(' - ')
        try:
            studio = Studio.objects.get(custom_id=studio_id)
        except Studio.DoesNotExist:
            print 'Studio not found in line: %s' % l
            continue
        prefix, suffix = r['Full Bundle ID'].rsplit('.', 1)
        try:
            app, created = App.objects.get_or_create(prj_code=r['AppCode'],
                bundle_id_prefix='%s.' % prefix, bundle_id_suffix=suffix,
                defaults={'prd_id': 'CD1%04i' % l,
                          'app_name': r['App Name in Store'],
                          'old_prj_code': r['AppCode Alternative'] or '',
                          'pub_name': r['App Name in Store'],
                          'app_id': r['Apple App_id'] or '',
                          'store_link': r['store link'],
                          'platform': 'I' if r['OS'] == 'iOS' else 'A',
                          'app_store': r['App Store'].strip(),
                          'studio': studio,
                          'editor': 'imported@smalltreemedia.com',
                          'status': 'V',
                          'flurry_key': r['Flurry ID'],
                          'valid_time': None,
                          'valid_person': 'imported@smalltreemedia.com'})
        except Exception, e:
            print '%s (line %s) %s' % (r['AppCode'], l, e)
            continue
        if not created:
#            print '%s (line %s) exists.' % (r['AppCode'], l)
            if not app.app_id:
                app.app_id = r['Apple App_id']
            if not app.flurry_key:
                app.flurry_key = r['Flurry ID']
            if not app.pub_name:
                app.pub_name = r['App Name in Store']
            if not app.old_prj_code:
                app.old_prj_code = r['AppCode Alternative'] or ''
            app.save()
            v1 = app.appversion_set.filter(code='1.0')[0]
            if not v1.date_released:
                v1.date_released = r['Initial release_date']
            if app.app_store == 'Google Play':
                if not v1.date_submitted:
                    v1.date_submitted = r['Initial release_date']
            v1.status = 'L'
            v1.save()
        else:
#            print 'created %s (line %s).' % (r['AppCode'], l)
            log_date = r['Initial release_date'].replace('-', '')
            count = AppVersion.objects.filter(log_id__startswith='PV%s9' % log_date).count()
            new_log_id = 'PV%s9%02i' % (log_date, (count + 1))
            date_submitted = r['Initial release_date'] if app.app_store == 'Google Play' else None
            AppVersion.objects.create(app=app, code='1.0', type='N',
                purpose='New App', editor='imported@smalltreemedia.com',
                owner=User.objects.get(email='imported@smalltreemedia.com').pk,
                status='L', date_submitted=date_submitted,
                date_released=r['Initial release_date'],
                log_id=new_log_id)


# import studios on PS - done
import csv
from app_info.models import *
with open('/home/develop/Live Apps Database - Studios.csv') as f:
    reader = csv.DictReader(f)
    for l, r in enumerate(reader, 2):
        code = r["code"]
        id = r["id"]
        name = r['studio_name']
        alt_name = r['alt_studio_name']
        copyright = r['copyright']
        main_domain = r['main_domain']
        alt_domain = r['alt_domain']
        if id == 'OLD':
            continue
        elif id == 'unassigned':
            Studio.objects.create(studio_code='%03i' % int(code), pub_name=name,
                prd_name=alt_name, copy_right=copyright, main_domain=main_domain,
                alt_domain=alt_domain)
        else:
            Studio.objects.filter(custom_id=id).update(studio_code='%03i' % int(code),
                prd_name=alt_name, copy_right=copyright, main_domain=main_domain,
                alt_domain=alt_domain)


# since submission request add new column review_status, init its value - done
from sub_info.models import *
SubInfo.objects.update(review_status='B')
rs = ReviewStatus.objects.filter(status='RE').values_list('sub_info', flat=True)
SubInfo.objects.filter(id__in=rs).update(review_status='C')
rs_rej = ReviewStatus.objects.filter(status='SR').values_list('sub_info', flat=True)
SubInfo.objects.filter(id__in=rs_rej).update(review_status='A')

# init projects' new column tier value 'T4' - done
from prd_order.models import *
Project.objects.update(tier='T4')

# init projects' new column studio - done
from prd_order.models import *
for p in Project.objects.all():
    if p.order:
        p.studio = p.order.studio
        p.save()


# for fixing the api bug - done
from app_info.models import *
for app in App.objects.filter(status='V', app_store='iTunes App Store'):
    if not app.store_link:
        app.store_link = 'https://itunes.apple.com/app/id%s?mt=8' % app.app_id
        app.save()


# init the appversion production team field - done
from app_info.models import *
for v in AppVersion.objects.filter(prd_team=None):
    team = v.get_team(False)
    if team:
        v.prd_team = team
        v.save()
    else:
        print '%s (V%s)' % (v.app_id, v.code)


# set GP apps' released date the day after submitted date - done
from app_info.models import *
import datetime
for v in AppVersion.objects.filter(app__app_store='Google Play', status__in='SL'):
    if v.date_submitted:
        if v.date_submitted == datetime.date.today():
            v.status = 'S'
            v.date_released = None
        else:
            v.date_released = v.date_submitted + datetime.timedelta(days=1)
        v.save()


# set division to studios
import MySQLdb
from app_info.models import UserGroup

ps_db=MySQLdb.connect(host='127.0.0.1', user='db_pts', passwd='db_pts',db='db_pts')
cur = ps_db.cursor()
i = 0
usergroups = UserGroup.objects.all()
for usergroup in usergroups:
    for c in usergroup.clouds.all():
        for studio in c.studio_set.all():
            i= i + 1
            cur.execute("""INSERT INTO app_info_usergroup_studios(id, usergroup_id, studio_id) VALUES(%(id)s, %(usergroup_id)s, %(studio_id)s)""", {'id': i, 'usergroup_id': usergroup.id, 'studio_id': studio.id })

cur.close()
ps_db.commit()
ps_db.close()
